package com.servlets;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloaderServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Map<String, String[]> urlMapping = new LinkedHashMap<String, String[]>(
				0);
		urlMapping
				.put("3/CS2201",
						new String[] {
								"C://project//Project_softwares//third.pdf",
								"application/pdf", "third.pdf" });
		urlMapping
				.put("3/CS2202",
						new String[] {
								"C://project//Project_softwares//fifth.pdf",
								"application/pdf", "fifth.docx" });

		String key = req.getParameter("semester").trim() + "/"
				+ req.getParameter("subject").trim();
		System.out.println(key);
		String[] value = urlMapping.get(key);
		String url = value[0];
		resp.setContentType(value[1]);
		resp.setHeader("Content-Disposition", "filename=\"" + value[2] + "\"");

		BufferedOutputStream writer = new BufferedOutputStream(
				resp.getOutputStream());
		BufferedInputStream reader = new BufferedInputStream(
				new FileInputStream(url));
		byte[] buf1 = new byte[1024];
		int length;
		while ((length = reader.read(buf1)) > 0) {
			writer.write(buf1, 0, length);
		}
		writer.close();
		reader.close();
	}

}
